/* The garbage collector for sockets hashtable. -- no longer 
 used 
 *
 */

package org.kth.dks.dks_comm;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.kth.dks.dks_node.DKSNode;

class ConnTableGC extends Thread {
	private final long SLEEPTIME = 1000 * 60 * 3; // 3 min,the main thraed
													// runs by this clock

	private ConnectionManager cm = null;

	public ConnTableGC(ConnectionManager cm) {
		this.cm = cm;
		this.setName(ConnTableGC.class.getName());
	} // constructor

	public void run() {
		while (true) {
			try {
				sleep(SLEEPTIME);
				Set allNeighbours = new HashSet();
				Collection nodes = cm.getAllNodes();
				Iterator iter = nodes.iterator();
				while (iter.hasNext()) {
					DKSNode node = (DKSNode) iter.next();
					allNeighbours.addAll(node.getNeighboursSet());
				}
				// we have all the neighbours as DKSRefs
				
				Set allConnHandler = cm.getConnHandler().getAllPeers();
				Set allPeers = new HashSet();
				iter = allConnHandler.iterator();
				while (iter.hasNext()) {
					allPeers.add(iter.next());
				}
				// we have all peers as DKSNetAddresses

				printSet(allPeers, "*******these are all my conns:");

				Set allNeigh = new HashSet();
				iter = allNeighbours.iterator();
				while (iter.hasNext()) {
					DKSRef ref = (DKSRef) iter.next();
					allNeigh.add(ref.getDKSNetAddress());
				}
				// we have all neighbours as DKSNetAddresses
				printSet(allNeigh, "*******these are all my neighbours:");
				
				allPeers.removeAll(allNeigh);
				
				printSet(allPeers, "*******about to remove following conns:");
				
				// remove connections to peers that are not out neighbours
				iter = allPeers.iterator();
				while (iter.hasNext()) {
					DKSNetAddress na = (DKSNetAddress) iter.next();
					cm.getConnHandler().removeConnection(na);
				}
			} catch (InterruptedException iexp) {
				iexp.printStackTrace();
			}
		} // while more keys
	} // while true
	
	public void printSet(Set set, String before) {
		System.out.println(before);
		Iterator iter = set.iterator();
		while (iter.hasNext()) {
			DKSNetAddress na = (DKSNetAddress) iter.next();
			System.out.print(na + ", ");
		}
	}
} // ConnTableGC class
